package com.moweilin.mo_utils.cli;

import com.beust.jcommander.Parameters;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
 * Created by moweilin on 2017/2/15.
 */
@Parameters(commandNames = {"version"},commandDescription = "show application version information.",commandDescriptionKey = "version")
public class VersionCommand {

    public boolean execute(Class mainClass) {
        URL url = mainClass.getResource(mainClass.getSimpleName()+".class");
        String protocol = url.getProtocol();
        String version = null;
        String title = null;
        if(!protocol.equalsIgnoreCase("file")){
            title = this.getClass().getPackage().getImplementationTitle();
            version = this.getClass().getPackage().getImplementationVersion();
        }else {
            try {
                Enumeration<URL> enumeration = mainClass.getClassLoader().getResources("META-INF/MANIFEST.MF");
                while (enumeration.hasMoreElements()){
                    URL u = enumeration.nextElement();
                    if("file".equals(u.getProtocol())){
                        Manifest manifest = new Manifest(u.openStream());
                        Attributes attributes = manifest.getMainAttributes();
                        title = attributes.getValue("Implementation-Title");
                        version = attributes.getValue("Implementation-Version");
                        break;
                    }
                }
            } catch (IOException e) {
//                throw new RuntimeException(e);
                System.err.println(e.getMessage());
            }

        }
        System.out.println("title:" + title);
        System.out.println("version:" + version);
        return true;
    }
}
